package com.rlax.framework.interceptor;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.rlax.framework.common.Consts;
import com.rlax.web.base.BaseWeiXinController;

/**
 * 微信授权 拦截器
 * 拦截微信请求，当未授权时转去授权
 * @author Rlax
 *
 */
public class WeiXinOauth2Interceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		boolean flag = false;
		
		if (inv.getController() instanceof BaseWeiXinController) {
			BaseWeiXinController c = (BaseWeiXinController) inv.getController();
			SnsAccessToken token = (SnsAccessToken) c.getSession().getAttribute(Consts.WEIXIN_SESSION_CODE);
			
			if (token == null) {
				String code = c.getPara("code");
				
				if (StrKit.isBlank(code)) {
					String appid = PropKit.get("weixin.appid");
					String redirect_uri = null;
					try {
						redirect_uri = URLEncoder.encode(PropKit.get("weixin.url") + c.getRequest().getRequestURI() + "?" + c.getRequest().getQueryString(), "UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					String state = "1";

					String url = SnsAccessTokenApi.getAuthorizeURL(appid, redirect_uri, state, false);
					// 重定向到授权页面
					c.redirect(url);
					flag = true;
				} else {
					c.getSession().setAttribute(Consts.WEIXIN_SESSION_CODE, SnsAccessTokenApi.getSnsAccessToken(PropKit.get("weixin.appid"), PropKit.get("weixin.appSecret"), code));
				}
			}
		}
		
		if (flag == false) {
			inv.invoke();
		}
	}

}
